package com.vcredit.creditcat.manager;

import org.apache.commons.lang.StringUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.vcredit.creditcat.api.IShareInfoManager;
import com.vcredit.creditcat.dto.shareInfo.ShareContext4VM;
import com.vcredit.creditcat.dto.shareInfo.ShareInfo;
import com.vcredit.creditcat.enumtype.ShareTypeEnum;
import com.vcredit.creditcat.exception.DataException;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.framework.util.VelocityUtil;

/**
 * 服务模块 Manager
 */
@Service(protocol = {"protocol1"}, version = "1.0")
public class ShareInfoManger implements IShareInfoManager {
  private static String share_template = "template/share_";
  private static String share_default = "template/share_default.vm";

  @Override
  public <T> ShareInfo processShareInfo(ShareContext4VM<T> shareContext) throws Exception {
    if (null == shareContext) {
      shareContext = new ShareContext4VM<T>();
    }
    ShareTypeEnum type =
        EnumExtUtil.getEnumOnValue(ShareTypeEnum.class,
            String.valueOf(shareContext.getShareType()), "code");
    String templateName = share_default;
    if (null == type) {//默认为分享到好友
      type = ShareTypeEnum.FRIEND;
      shareContext.setShareType(type.getCode());
    }
    if (!StringUtils.isBlank(shareContext.getActivityCode())) {
      templateName = share_template + shareContext.getActivityCode() + ".vm";
    }
    return getShareInfoByVM(templateName, "shareContext", shareContext);
  }

  private ShareInfo getShareInfoByVM(String templateName, Object... obj) throws Exception {
    String vmFull = VelocityUtil.templateToText(templateName, obj);
    if (StringUtils.isBlank(vmFull)) {
      throw new DataException("内容不存在。");
    }
    String[] vmDatas = vmFull.split("@#@");
    if (4 != vmDatas.length) {
      throw new DataException("格式错误。");
    }
    return new ShareInfo(vmDatas[2], vmDatas[3], vmDatas[0], vmDatas[1]);
  }
}
